package comp6231.project.replica.dimitri;
/**
 * Distributed Retail System
 * Oct 10, 2012 
 */


import java.io.IOException;
import java.net.DatagramPacket;
import java.net.DatagramSocket;
import java.net.SocketException;

/**
 * @author dimitri.tiago
 *
 */
public class UDPRetailStockServerProcessorThread implements Runnable
{
	DatagramSocket aSocket;
	DatagramPacket request;

	RetailStoreStock stock;

	public UDPRetailStockServerProcessorThread(DatagramSocket aSocket, DatagramPacket request, RetailStoreStock stock)
	{
		this.aSocket = aSocket;
		this.request = request;
		this.stock   = stock;
	}

	@Override
	public void run()
	{
		try
		{
			// process request
			String requestData = new String(request.getData()).trim();
			if (requestData.contains("buy"))
			{
				int itemsFromStock	    = 0;
				int itemID 		    = Integer.parseInt((requestData.split(" "))[1]);
				int numOfItemsRequested = Integer.parseInt((requestData.split(" "))[2]);
				int itemsInStock 	    = stock.checkItemsStock(itemID);
				if (itemsInStock >= numOfItemsRequested) // check that we have enough items in stock for itemid
				{
					// enough items in stock to satisfy request. remove them.
					itemsFromStock = stock.remItemsFromStock(itemID, numOfItemsRequested);
				}
				else
				{
					// not enough items to satisfy request. remove all.
					itemsFromStock = stock.remItemsFromStock(itemID, itemsInStock);
				}

				// send reply
				byte [] responseData = String.valueOf(itemsFromStock).getBytes();
				DatagramPacket reply = new DatagramPacket(responseData, 
						String.valueOf(itemsFromStock).length(), request.getAddress(), request.getPort());
				aSocket.send(reply);
			}
			else if (requestData.contains("check stock"))
			{
				int itemID 		 = Integer.parseInt((requestData.split(" "))[2]);
				int itemsInStock 	 = stock.checkItemsStock(itemID); // get items in stock for item id

				// send reply
				byte [] responseData = String.valueOf(itemsInStock).getBytes();
				DatagramPacket reply = new DatagramPacket(responseData, 
						String.valueOf(itemsInStock).length(), request.getAddress(), request.getPort());
				aSocket.send(reply);
			}
		}
		catch (SocketException e)
		{
			System.out.println("Socket: " + e.getMessage());
		}
		catch (IOException e) 
		{
			System.out.println("IO: " + e.getMessage());
		}
	}
}